package ar.com.e2solver.solver.localsearch;

import java.util.List;

import ar.com.e2solver.exception.BusinessException;
import ar.com.e2solver.solver.Individual;
import ar.com.e2solver.solver.Population;
import ar.com.e2solver.solver.operator.impl.SwapAndRotateMutationOperator;

public class ClimbWorker implements Runnable {

	private Individual individual;
	private List<Individual> resultList;
	private int internalNumber;
	
	public ClimbWorker(Individual individual, List<Individual> resultList, int internalNumber){
		this.individual = individual;
		this.resultList = resultList;
		this.internalNumber = internalNumber;
	}
	
	public void run() {
		try {
			Individual result = climb(this.individual);
			this.resultList.add(result);
			
		} catch (BusinessException e) {
			System.out.println("ClimbWorkerError" + internalNumber);
		}
	}
	
	private Individual climb(Individual individual) throws BusinessException {
		Individual result = individual;
		int cant = individual.getPuzzle().getRowsNumber() * individual.getPuzzle().getColumnNumbers();
		int cantDeep = individual.getPuzzle().getRowsNumber() * individual.getPuzzle().getColumnNumbers() * 10;
		
		for (int i = 0; i < cantDeep; i++) {	
			Population population = new Population();
			
			for (int j = 0; j < cant; j++) {
				population.add(getNeighbor(result));
			}
			result = population.getBestIndividual();
		}
		
		return result;
	}

	private Individual getNeighbor(Individual individual) throws BusinessException {
		Individual result;
		
		result = SwapAndRotateMutationOperator.getInstance().operate(individual);
		return result;
	}

}
